package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.feign.wemedia.IWemediaClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserFanService;
import com.heima.user.service.ApUserFollowService;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private IWemediaClient wemediaClient;

    @Autowired
    private ApUserFollowService apUserFollowService; // 用户关注
    @Autowired
    private ApUserFanService apUserFanService; //用户粉丝
    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * 用户关注与取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult handlerUserRelation(UserRelationDto dto) {
        //1.入参校验
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断是否登录
        ApUser apUser = ApUserThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        apUser = apUserMapper.selectById(apUser.getId());
        //文章作者的id
        Integer authorId = dto.getAuthorId();
        //feign远程调用自媒体微服务,根据作者的id查询作者的信息
        ResponseResult responseResult = wemediaClient.findWmUserById(authorId);
        WmUser wmUser = null;
        if (responseResult.getCode() == 200) {
            wmUser = JSON.parseObject(responseResult.getData().toString(), WmUser.class);
            if (wmUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "作者id有误!");
            }
        }

        if (dto.getOperation() == 0) {//用户关注
            //如果是关注操作
            //3.将文章作者写入到当前登录用户的关注列表中 ,同步更新数据库表ap_user_follow
            cacheService.zAdd(BehaviorConstants.USER_FOLLOW + apUser.getId(),
                    authorId.toString(),
                    System.currentTimeMillis());
            //4.将当前登录用户写入到 文章作者的粉丝列表中 ,同步更新数据库表ap_user_fan
            cacheService.zAdd(BehaviorConstants.USER_FAN + authorId,
                    apUser.getId().toString(),
                    System.currentTimeMillis());

            //更新db
            //当前登录用户关注列表中,加入当前文章作者
            ApUserFollow apUserFollow = ApUserFollow.builder()
                    .userId(apUser.getId())
                    .followId(authorId)
                    .followName(wmUser.getName())
                    .level((short) 1)
                    .isNotice((short) 1)
                    .createdTime(new Date())
                    .build();
            apUserFollowService.save(apUserFollow);
            //当前文章作者的粉丝列表中,加入当前登录的用户
            ApUserFan apUserFan = ApUserFan.builder()
                    .userId(authorId)
                    .fansId(apUser.getId())
                    .fansName(apUser.getName())
                    .level((short) 0)
                    .createdTime(new Date())
                    .isDisplay((short) 1)
                    .isShieldLetter((short) 1)
                    .isShieldComment((short) 1)
                    .build();
            apUserFanService.save(apUserFan);

        } else {//用户取消关注
            //如果是取消关注操作
            //对应的删除 关注列表 和 粉丝列表,同时相应的更新数据库
            cacheService.zRemove(BehaviorConstants.USER_FOLLOW + apUser.getId(),
                    authorId.toString());
            cacheService.zRemove(BehaviorConstants.USER_FAN + authorId,
                    apUser.getId().toString());
            //更新db
            //删除当前登录用户关注表中该文章作者的数据
            apUserFollowService.remove(Wrappers.<ApUserFollow>lambdaQuery()
                    .eq(ApUserFollow::getUserId, apUser.getId())
                    .eq(ApUserFollow::getFollowId, authorId));
            //删除该文章作者的粉丝列表中,当前登录用户的数据
            apUserFanService.remove(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, authorId)
                    .eq(ApUserFan::getFansId, apUser.getId()));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
